package com.itlangzi.mybatis.dialect;

import com.alibaba.druid.util.JdbcConstants;
import com.itlangzi.mybatis.dialect.helper.DialectEnum;
import com.itlangzi.mybatis.dialect.helper.DialectHelper;

/**
 * Oracle 分页方言
 */
public class OracleDialect implements Dialect {

	@Override
	public boolean supportsPage() {
		return true;
	}

	@Override
	public String buildCountSQL(String originalSQL) {
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT COUNT(1) TOTAL FROM ( ").append(DialectHelper.getNoneOrderBySQL(originalSQL, JdbcConstants.ORACLE)).append(" ) T ");
		return sb.toString();
	}

	@Override
	public String buildPageSQL(String originalSQL, Integer page, Integer size) {
		StringBuilder sqlBuilder = new StringBuilder(originalSQL.length() + 120);
		sqlBuilder.append("SELECT * FROM ( ");
		sqlBuilder.append(" SELECT TMP_PAGE.*, ROWNUM ROW_ID FROM ( ");
		sqlBuilder.append(originalSQL);
		sqlBuilder.append(" ) TMP_PAGE)");
		sqlBuilder.append(" WHERE ROW_ID <= ");
		sqlBuilder.append(page * size);
		sqlBuilder.append(" AND ROW_ID > ");
		sqlBuilder.append((page - 1) * size);
		return sqlBuilder.toString();
	}
	@Override
	public String getDialectName() {
		return DialectEnum.ORACLE.getDbName();
	}

}
